package com.zhouzhou.fastjava.query.executors;

import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLOrderBy;
import com.alibaba.druid.sql.ast.expr.SQLQueryExpr;
import com.alibaba.druid.sql.ast.statement.SQLSelectItem;
import com.alibaba.druid.sql.ast.statement.SQLSelectQueryBlock;
import com.zhouzhou.fastjava.query.AbstractLessSubQueryExecutor;
import com.zhouzhou.fastjava.query.QueryConfiguration;
import com.zhouzhou.fastjava.query.QueryExecutor;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.Map;

/**
 * Created by mojianlan on 10/9/2017.
 */
public class LessSubQueryJdbcTemplateExecutor extends AbstractLessSubQueryExecutor implements QueryExecutor {

    private JdbcTemplate jdbcTemplate;

    public LessSubQueryJdbcTemplateExecutor(QueryConfiguration configuration) {
        super(configuration);
        jdbcTemplate = new JdbcTemplate(configuration.getDataSource());
    }

    @Override
    public <T> T queryForObject(String sql, Class<T> requiredType, Object... args) {
        return jdbcTemplate.queryForObject(sql, requiredType, args);
    }

    @Override
    public List<Map<String, Object>> queryForList(String sql, Object... args) {
        return jdbcTemplate.queryForList(sql, args);
    }

    @Override
    protected Long getTotal(String selectSQL, Object[] sqlParams) {
        SQLQueryExpr sqlExpr = (SQLQueryExpr) SQLUtils.toMySqlExpr(selectSQL);
        SQLSelectQueryBlock queryBlock = sqlExpr.getSubQuery().getQueryBlock();
        List<SQLSelectItem> selectListItems = queryBlock.getSelectList();
        selectListItems.clear();
        selectListItems.add(new SQLSelectItem(SQLUtils.toMySqlExpr("count(1)")));
        SQLOrderBy sqlOrderBy = queryBlock.getOrderBy();
        if (sqlOrderBy != null && sqlOrderBy.getItems() != null) {
            sqlOrderBy.getItems().clear();
        }
        String countSql = SQLUtils.toMySqlString(queryBlock);
        return this.queryForObject(countSql, Long.class, sqlParams);
    }

}
